<template>
  <div class="gotop" v-if="flag" @click="goTop()">
    <van-icon name="arrow-up" />
  </div>
</template>

<script>
import Vue from 'vue'
import { Icon } from 'vant'
Vue.use(Icon)
export default {
  data () {
    return {
      flag: false // 返回顶部标识符
    }
  },
  mounted () {
    document.getElementById('box').addEventListener('scroll', this.handleScroll, false)
  },
  methods: {
    // 返回顶部图标显示事件
    handleScroll () {
      const scrollTop = document.getElementById('box').scrollTop
      if (scrollTop > 500) {
        this.flag = true
      } else {
        this.flag = false
      }
      // console.log(scrollTop, this.flag)
    },
    // 返回顶部事件
    goTop () {
      // console.log(document.getElementById('box').scrollTop)
      const back = setInterval(fa, 20)
      function fa () {
        var scrollTop = document.getElementById('box').scrollTop
        const a = scrollTop - scrollTop / 5
        document.getElementById('box').scrollTop = a
        if (a < 1) {
          document.getElementById('box').scrollTop = 0
          clearInterval(back)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.gotop {
  z-index: 1000;
  position: fixed;
  right:.1rem;
  bottom:.6rem;
  background-color: #ffe7e8;
  width: .3rem;
  height: .3rem;
  border-radius: 50%;
  .van-icon {
    font-size:.25rem;
    padding: 0 .02rem;
  }
}
</style>
